package com.hippo.javacore.javaiostream.iostream;

import java.io.*;

/**
 * @ClassName CopyFile
 * @Description TODO 文件复制
 * @Author tangxl
 * @create 2023-04-06 16:11
 **/
public class CopyFile {
    public static void main(String[] args) {
        String srcPath = "study-commons/java-file-iostream/src/main/resources/file";
        System.out.println("复制是否成功："+copyFile(srcPath, srcPath + File.separator + "copy", "a.txt"));
    }

    /**
     * TODO 文件复制
     * @param srcPath 源文件路径
     * @param destPath 目标文件路径
     * @param fileName 文件名
     * @return
     */
    public static boolean copyFile(String srcPath, String destPath, String fileName){
        // 判断目标文件夹是否存在，不存在则创建
        File destFile = new File(destPath);
        if(!destFile.exists()){
            destFile.mkdirs();
        }
        // 复制文件,try()中的资源会自动关闭
        try(InputStream is = new FileInputStream(srcPath+ File.separator + fileName);
            OutputStream os = new FileOutputStream(destPath + File.separator + fileName)){
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
}
